package com.ffcs.web.utils;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.util.Assert;

public class ThreeDesTools {
	private static String algorithm = "DESede";
	
	/*
	 * 3DES加密
	 */
	public static String encrypt3DES(byte[] str, String key) {
		byte[] bytesKey;
		try {
			bytesKey = Hex.decode(key);
			Security.addProvider(new BouncyCastleProvider());
			Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
			cEnc.init(1, new SecretKeySpec(bytesKey, algorithm), 
					new IvParameterSpec(Hex.decode("0102030405060708")));
			byte[] bytes3DES = cEnc.doFinal(str);

			//return Encode.base64Encode(bytes3DES);
			return new String(BASE64.encode(bytes3DES));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String encrypt3DESStr(byte[] str, String key) {
		byte[] bytesKey;
		try {
			bytesKey = Hex.decode(key);
			Security.addProvider(new BouncyCastleProvider());
			Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
			cEnc.init(1, new SecretKeySpec(bytesKey, algorithm), 
					new IvParameterSpec(Hex.decode("0102030405060708")));
			byte[] bytes3DES = cEnc.doFinal(str);

			//return Encode.base64Encode(bytes3DES);
			return new String(BASE64.encode(bytes3DES));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/*
	 * 3DES解密
	 */
	public static String decrypt3DES(String str, String key) {
		Assert.hasText(str);
		Assert.hasText(key);
		
		byte[] bytesKey;
		try {
			bytesKey = Hex.decode(key);
			Security.addProvider(new BouncyCastleProvider());
			Cipher cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
			cEnc.init(2, new SecretKeySpec(bytesKey, algorithm), 
					new IvParameterSpec(Hex.decode("0102030405060708")));
			byte[] bytes3DES = cEnc.doFinal(BASE64.decode(str));

			return new String(bytes3DES);
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}
	
//	public static void main(String[] args) {
//		String content = "123456";
		String key = "666663736361696C696E673121402324255E262A28295F2B";
//		String crytoContent = encrypt3DES(content,key);
//		System.out.println("明文:" + content);
//		System.out.println("密文:" + crytoContent);
//		System.out.println("解密:" + decrypt3DES(crytoContent,key));
//	}
	public static void main(String[] args) {
		String key = "666663736361696C696E673121402324255E262A28295F2B";
		System.out.println(ThreeDesTools.encrypt3DES("1234".getBytes(),key));
	}
}
